package com.efuture.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @ClassNAME CopyDirectory
 * @Description 该类主要实现目录的拷贝功能
 * @Author zhaoshanshan
 * @Date 2021/9/8 11:48 下午
 * @Version 1.0
 */
public class CopyDirectory {

    public static void main(String[] args) {

        File sourcePath = new File("/Users/zhaoshanshan/Desktop/临时");
        File targetPath = new File("/Users/zhaoshanshan/Desktop/工具");
        copyDirectory(sourcePath,targetPath);
        System.out.println("拷贝完成");
    }
    private static void copyDirectory(File sourcePath,File targetPath){
       try{
           if(sourcePath.exists()&&sourcePath.isFile()){
               System.out.println("直接拷贝");
               //直接拷贝
               FileInputStream fis = new FileInputStream(sourcePath);
               String sourcePathTemp = "/Users/zhaoshanshan/Desktop/临时";
               String path = targetPath.getAbsolutePath()+sourcePath.getAbsolutePath().substring(sourcePathTemp.length(),sourcePath.getAbsolutePath().length());
               targetPath = new File(path);
               FileOutputStream fos = new FileOutputStream(targetPath);
               byte[] bytes = new byte[1024];
               int readCount = -1;
               while ((readCount = fis.read(bytes))!=-1){
                   fos.write(bytes,0,readCount);
               }
               fos.flush();
               fis.close();
               fos.close();
               return;
           }
           else if(sourcePath.exists()){//说明是个目录
               //创建目录
               File[] files = sourcePath.listFiles();
               for (File f:files){
                   System.out.println(f.getAbsolutePath());
                   if(f.isDirectory()){
                       String targetTempPath = "/Users/zhaoshanshan/Desktop/临时";
                       String path = "/Users/zhaoshanshan/Desktop/工具"+f.getAbsolutePath().substring(targetTempPath.length(),f.getAbsolutePath().length());
                       File file = new File(path);
                       if(!file.exists()){
                           file.mkdirs();
                       }
                   }
                   copyDirectory(f,targetPath);
               }
           }
       }catch (Exception e){
           e.getStackTrace();
       }



    }
}